<?php

class ZSql {
    /* $match_start 前端
      $$match_end  后端
     */

    static public function substr_content_db($orgin_content, $contents, $match_start, $match_end) {
        if (empty($orgin_content) || empty($match_end))
            return '';
        $a = strpos($orgin_content, $match_start);
        $start_len = strlen($match_start);
        $sln = $a + $start_len;
        $start_str = substr($orgin_content, 0, $sln);
        $end_str = strstr($orgin_content, $match_end);
        $text = $start_str . $contents . $end_str;
        return $text;
    }

    static public function substr_content($orgin_content, $match_start, $match_end, $isJieQu = false) {

        if (empty($orgin_content) || empty($match_start) || empty($match_end))
            return '';

        echo $pos_start = stripos($orgin_content, $match_start);
        exit;
        if (empty($pos_start))
            return '';
        $temp_start = substr($orgin_content, $pos_start);
        $pos_end = stripos($temp_start, $match_end);
        if (empty($pos_end))
            return '';

        if ($isJieQu) {
            $result = substr($temp_start, strlen($match_start), $pos_end - strlen($match_start));
        } else {
            $result = substr($temp_start, 0, $pos_end + strlen($match_end));
        }
        return $result;
    }

    static public function substr_content_array($orgin_content, $match_start, $match_end, $isJieQu = false) {
        if (empty($orgin_content) || empty($match_start) || empty($match_end))
            return '';

        for ($i = 0; $i < 100; $i++) {
            $pos_start = ''.stripos($orgin_content, $match_start);
            $nums=strlen($pos_start);
            if ($nums==0){
                break;
            }
            
            $temp_start = substr($orgin_content, $pos_start);
            $pos_end = stripos($temp_start, $match_end);
            if (empty($pos_end))
                break;
            if ($isJieQu) {
                $result[] = substr($temp_start, strlen($match_start), $pos_end - strlen($match_start));
            } else {
                $result[] = substr($temp_start, 0, $pos_end + strlen($match_end));
            }
            $orgin_content = substr($orgin_content, $pos_end, strlen($orgin_content));
        }

        return $result;
    }

    static public function match_content($orgin_content, $preg) {
        preg_match($preg, $orgin_content, $match);
        return $match;
    }


    /*
     * 处理sql文件的截取方法
     * */

    static public function substr_content_sql($content, $match_start, $match_end) {
        if (empty($content) || empty($match_end))
            return '';
        $content = strstr($content, $match_end);
        $langth = strlen($content);
        $content = substr(strval($content), 1, $langth);
        $start_lan = strpos(strval($content), strval($match_start));
        $end_lan = strpos(strval($content), strval($match_end));
        $start_str = substr(strval($content), $start_lan, $end_lan);
        return $start_str;
    }

    /*
     * 截取 $match_start 到 $match_end
     * */

    static public function substr_content_sqls($content, $match_start, $match_end) {
        if (empty($content) || empty($match_end))
            return '';
        $start_lan = strpos($content, $match_start);
        $end_lan = strpos($content, $match_end);
        $start_str = substr($content, $start_lan, $end_lan);
        return $start_str;
    }
    
    
    static public function genSchoolModel() {
        $patch_s = Yii::getPathOfAlias('webroot') . "/../app/protected/modules/dynamic/models";
        //$publics = file_get_contents($patch_s . "/uptb.txt");
$publics=<<<EOF
{
        private static \$tableName ;

        public function __construct(\$table_name = '') {
            if (\$table_name === null) {
                parent::__construct(null);
            } else {
                self::\$tableName = "{{".\$table_name."_tmp_type}}";
                parent::__construct();
            }
        }

        /**
         * Returns the static model of the specified AR class.
         * @param string \$className active record class name.
         * @return Grade the static model class
         */
        public static function model(\$className = __CLASS__) {
            return parent::model(\$className);
        }

        /**
         * @return string the associated database table name
         */
        public function tableName() {
            return self::\$tableName;
        }

	/**
	 * 
EOF;

        if (is_dir($patch_s)) {
            $dir = opendir($patch_s);
            if ($dir) {
                while (($file = readdir($dir)) !== false) {
                    if ($file != "." && $file != ".." && strtoupper(substr($file, 0, 1)) === 'D') {
                        
                        $patch = $patch_s . '/' . $file;
                        $content = file_get_contents($patch);
                        if(!empty($content)){
                            $isHas = preg_match('/private static \$tableName/i', $content, $temp);
                            if (!$isHas) {
                                $tbName = preg_match('/\{\{[0-1]+([a-z_]*)\}\}/i', $content, $temp) ? $temp [1] : "";
                                if (!empty($tbName)) {

                                    $publics = str_replace("_tmp_type", $tbName, $publics);
                                    $uptb = self::substr_content_db($content, $publics, 'CActiveRecord', "@return array validation rules for model attributes.");
                                    $ftble = fopen($patch, "w");
                                    fwrite($ftble, $uptb);
                                    echo $patch . "数据变更完成<br>";
                                }
                            }
                        }
                    }
                }
                closedir($dir);
            }
        }
    }

    /*
     * 读取sql文件 并生成yiisql文件形式
     * */

    static public function genSchoolSql($content) {
        $contentul = ZSql::substr_content_array($content, 'CREATE', ';', false);
        $patch_s = Yii::getPathOfAlias('webroot') . "/../app/protected/modules/dynamic/models";
        $path_file = $patch_s . '/ZDynamic.php';
        foreach ($contentul as $sql) {
            if (!empty($sql)) {
                //创建sql编译成文件
                $conunt = str_replace('zhxy_100001', '{{".$aa_school_sn."}}', $sql);
                $conunt_sql = str_replace('CREATE TABLE', 'CREATE  TABLE IF NOT EXISTS', $conunt);
                $contentuls = ZSql::substr_content_sqls($conunt_sql, 'CREATE TABLE', '(');

                //获取原文件
                $fileconunts = file_get_contents($path_file);
                $conuntz = strstr($fileconunts, $contentuls);
                if (!empty($conuntz)) {
                   $contentulzs = ZSql::substr_content_sqls($conuntz, $contentuls, ';');
                   $text = str_replace($contentulzs.";", $conunt_sql, $fileconunts);
                   $ftble = fopen($path_file, 'w');
                    fwrite($ftble, $text);
                } else {
                    
                    $pos_end = stripos($fileconunts, "}//endfunc");
                    $first_c = substr($fileconunts, 0, $pos_end);
                    $last_c = substr($fileconunts, $pos_end, strlen($fileconunts));
                    
                    $middle_c="\t\$sql=\"".$conunt_sql."\";\n";
                    $middle_c.="\t\$result = Yii::app()->db->createCommand(\$sql);\n\t\$result->execute();\n\t";
                    $total_c=$first_c.$middle_c.$last_c;
                    $ftble = fopen($path_file, 'w');
                    fwrite($ftble, $total_c);
                    
                }

            }
        }
    }
    
    static public function getNew_sql($aa_school_sn) {
    	$patch    = Yii::getPathOfAlias('webroot') . "/../app/protected/modules/dynamic/db";
    	$patch_s  = $patch."/project_aa100_1.sql";
        $content  = file_get_contents($patch_s);
        $sql=preg_replace("/zhxy_1100001/","zhxy_".$aa_school_sn,$content);
        return $sql;
    
    }
    
    static public function getMVC() {
        $patch_s = Yii::getPathOfAlias('webroot') . "/../app/protected/modules/";
        if (is_dir($patch_s)) {
            $dir = opendir($patch_s);
            if ($dir) {
                while (($file = readdir($dir)) !== false) {
                    if ($file != "." && $file != ".." && !preg_match("/\./", $file)) {
                       
                        $dirT = $patch_s."/".$file."/controllers";
                        if(is_dir($dirT)){
                            
                            $dir1 = opendir($dirT);
                            if ($dir1) {
                                while (($file1 = readdir($dir1)) !== false) {
                                    
                                    if ($file1 != "." && $file1 != ".." && preg_match("/.php/", $file1)) {
                                        //echo "<br>".$file." ".$file1;
                                        $m=$file;
                                        preg_match_all("/([0-9a-zA-Z_]+)Controller/", $file1,$matche);
                                        if(isset($matche[1]) && isset($matche[1][0])){
                                            $c=$matche[1][0];
                                            
                                            $patch = $dirT . '/' . $file1;
                                            $content = file_get_contents($patch);
                                            preg_match_all("/action([0-9a-zA-Z_]+)\(\)/", $content, $matches);
                                            if(isset($matches[1])){
                                                foreach ($matches[1] as $key => $value) {
                                                    echo $m." ".$c." ".$value;
                                                    echo "<br>";
                                                }
                                            }
                                            
                                        }
                                        echo "<br>";
                                        
                                        
                                    }
                                }
                            }
                        }
                        
                    }
                }
            }
        }
    }

}
